package com.family.menage.service.impl;

import com.family.menage.controller.vo.CityStateVo;
import com.family.menage.controller.vo.CitycountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.family.common.utils.PageUtils;
import com.family.common.utils.Query;

import com.family.menage.dao.AddressDao;
import com.family.menage.entity.AddressEntity;
import com.family.menage.service.AddressService;


@Service("addressService")
public class AddressServiceImpl extends ServiceImpl<AddressDao, AddressEntity> implements AddressService {
    @Autowired
    private AddressDao addressDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AddressEntity> page = this.page(
                new Query<AddressEntity>().getPage(params),
                new QueryWrapper<AddressEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<AddressEntity> listWithtree() {
        List<AddressEntity> addressEntities = baseMapper.selectList(null);
        List<AddressEntity> collect = addressEntities.stream().filter(e -> e.getPid()==0).map(m -> {
            m.setChildrens(getChildrens(m, addressEntities));
            return m;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<CitycountVo> cityStateCount() {
        return addressDao.cityStateCount();
    }

    @Override
    public List<CityStateVo> cityStateByPid(Integer pid) {
        return addressDao.cityStateByPid(pid);
    }

    @Override
    public List<AddressEntity> cityAll(String firstword) {
        return addressDao.cityAll(firstword);
    }


    private List<AddressEntity> getChildrens(AddressEntity addressEntity, List<AddressEntity> addressEntities) {
        if(addressEntities!=null&&addressEntities.size()>0){
            List<AddressEntity> collect = addressEntities.stream().filter(e -> {
                return e.getPid() == addressEntity.getId();
            }).map(m -> {
                m.setChildrens(getChildrens(m, addressEntities));
                return m;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

}